package com.wanghlme.leetcodecn;

import java.util.Stack;

/**
 * <p>剑指 Offer 06. 从尾到头打印链表</p>
 *
 * @author wanghlme
 * @version 1.0
 */
public class LC_JZ06 {
    public static void main(String[] args) {

    }

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public int[] reversePrint(ListNode head) {
            Stack<Integer> res = new Stack<>();
            reverse(null, head, res);
            int[] result = new int[res.size()];
            int i = 0;
            while (!res.isEmpty()) {
                result[i++] = res.pop();
            }
            return result;
        }

        private ListNode reverse(ListNode pre, ListNode cur, Stack<Integer> result) {
            if (cur == null) return pre;
            ListNode tmp = cur.next;
            cur.next = pre;
            result.push(cur.val);
            return reverse(cur, tmp, result);
        }
    }
}
